package org.suze.framework.base.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.suze.framework.base.BaseConverter;
import org.suze.framework.base.BaseFacade;
import org.suze.framework.base.BaseService;
import org.suze.framework.base.Result;
import org.suze.framework.base.enums.RemoteEnum;
import org.suze.framework.base.page.PageForm;
import org.suze.framework.base.page.PageVO;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

/**
 * @description: BaseFacadeImpl，相关功能模块应该继承此类
 * @Date : 2019/5/31 下午10:04
 * @Author : 石冬冬-Seig Heil
 * @param <V> 页面显示VO对象
 * @param <E> 数据库实体对象
 * @param <P> 查询主键
 * @param <F> 查询条件Form对象
 */
@Slf4j
public abstract class BaseFacadeImpl<V extends Serializable,E extends Serializable,P extends Serializable,F extends Serializable> implements BaseFacade<V,E,P,F> {
    /**
     * service
     */
    protected BaseService<E,P,F> service;

    /**
     * 是否修改操作
     * @param record
     * @return
     */
    protected abstract boolean isModify(E record);

    /**
     * VO转换器
     * @return
     */
    protected abstract BaseConverter<V,E> converter();

    @Autowired
    public void setService(BaseService<E, P, F> service) {
        this.service = service;
    }

    @Override
    public Result<PageVO<V>> loadRecords(PageForm<F> form) {
        List<V> voList = Collections.emptyList();
        int count = 0;
        try {
            List<E> queryList = service.queryByPage(form);
            count = service.queryCount(form);
            voList = converter().convertList(queryList);
        } catch (Exception e) {
            log.error("loadRecords exception,form={}", JSON.toJSON(form),e);
            return Result.failInServer(PageVO.newInstance(count,voList));
        }
        return Result.suc(PageVO.newInstance(count,voList));
    }

    @Override
    public Result queryRecord(P primaryKey) {
        E entity = service.queryRecord(primaryKey);
        if(null == entity){
            return Result.fail(RemoteEnum.WARN_EMPTY_RECORD);
        }
        return Result.suc(converter().convert(entity));
    }

    @Override
    public Result<String> saveRecord(E record) {
        if(isModify(record)){
            service.updateRecord(record);
        }else{
            service.insertRecord(record);
        }
        return Result.suc();
    }

    @Override
    public Result<String> deleteRecord(P primaryKey) {
        service.deleteRecord(primaryKey);
        return Result.suc();
    }

    @Override
    public Result<String> modifyStatus(E record) {
        service.updateByPrimaryKeySelective(record);
        return Result.suc();
    }
}
